package com.kuizii.base.web.controller;

import com.kuizii.base.domain.BaseResponse;
import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Api(value = "日志管理",hidden = true)
@RestController
@RequestMapping(name = "log")
@Profile(value = {"dev"})
public class LogController {

    @Value("${management.endpoint.logfile.external-file:}")
    String defaultLogPath;

    @Value("${logging.path:}")
    String logDir;


    public String getLogDir() {
        if (StringUtils.isEmpty(logDir)) {
            return System.getProperty("user.dir") + File.separator + "logs/";
        }
        return logDir;
    }


    Map getLogFiles() {

        String[] list = new File(getLogDir()).list();
        Map map = new HashMap(list.length);
        int i = 1;
        for (String s : list) {
            map.put(i, s);
            i++;
        }
        return map;
    }

    @GetMapping(value = "listLogs")
    public BaseResponse listLogs(HttpServletRequest request) {

        return BaseResponse.ok(getLogFiles());
    }

    @GetMapping(value = "downloadLog")
    public void downloadLog(Integer index, HttpServletResponse response) {

        String logFile = "";
        if (index == null) {
            logFile = defaultLogPath;
            response.setHeader("Content-Disposition", "attachment;filename=info.log");
        } else if (index > getLogFiles().size()) {
            throw new RuntimeException("超出日志文件选择范围");
        } else {
            String filename = (String) getLogFiles().get(index);
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);

            logFile = getLogDir() + filename;
        }
        try {
            IOUtils.copy(FileUtils.openInputStream(new File(logFile)), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("日志下载失败");
        }
    }
}
